import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CustomizedCouponService } from '../services/customized-coupon.service';
import { CustomizeDescentService } from '../services/customized-descent.service';

@Component({
  selector: 'app-customized-descent-edit',
  templateUrl: './customized-descent-edit.component.html',
  styleUrls: ['./customized-descent-edit.component.scss'],
  providers: [DatePipe]
})
export class CustomizedDescentEditComponent implements OnInit {

  routeParams: any = {};
  formParams: any = {
    status: 5,
    type: 1, // 活动类型 1：满减 2：满折 3：多件折扣
    name: '', // 活动名称
    showCopy: '', // 前端标题
    remark: '', // 备注
    orderLimitMoney: '', // 门槛（满多少）
    limitSmall: '', // 减免额度 | 折扣力度
    limitBig: '', // 最高减免金额
    overlayFlag: '', // 倍数减免 0：否 1：是
    isPlusCoupons: 0, // 是否可以叠加优惠券(0是 1否)

    userType: 0, // 适用用户 0：不限制 1：C端 2：B端
    beginTime: '', // 生效开始时间
    endTime: '', // 生效结束时间
  };

  // 生效时间
  takeEffectDates: any[] = [];

  // 适用用户
  userTypeOptions: any = [
    {value: 0, label: '不限制'},
    {value: 1, label: 'C端'},
    {value: 2, label: 'B端'}
  ];

  // 适用品类
  categoryOptions: any = [];
  selectedCategory: any = [];

  // 多件折扣Table
  discountTable: any = [];

  releaseLoading = false;
  preservationLoading = false;

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private customizedCouponService: CustomizedCouponService,
    private services: CustomizeDescentService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadAdzGoodTypeList();
    if (['1', '3'].includes(this.routeParams.type)) {
      this.loadDetails();
    }
  }

  // 查询适用品类
  async loadAdzGoodTypeList() {
    const {code, data, message}: any = await this.customizedCouponService.getAdzGoodTypeList();
    if (code === 0) {
      this.categoryOptions = data || [];
    } else {
      this.message.error(message);
    }
  }

  async loadDetails() {
    let params = {
      id: this.routeParams.id,
      page: 1,
      pageSize: 10
    }
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const { code, data, message }: any = await this.services.getDescentDetail(params);
    this.message.remove(messId);

    if (code === 0) {
      const { promotionInfo } = data || {};
      
      this.formParams.status = promotionInfo.status; // 状态
      this.formParams.type = promotionInfo.type; // 类型
      this.formParams.name = promotionInfo.name; // 活动名称
      this.formParams.showCopy = promotionInfo.showCopy; // 前端标题
      this.formParams.remark = promotionInfo.remark || ''; // 备注
      this.formParams.isPlusCoupons = promotionInfo.isPlusCoupons; // 是否可以叠加优惠券

      this.formParams.orderLimitMoney = promotionInfo.orderLimitMoney || ''; // 优惠门槛
      this.formParams.limitSmall = promotionInfo.limitSmall || ''; // 减免额度 | 折扣力度
      this.formParams.overlayFlag = this.isEmpty(promotionInfo.overlayFlag) ? '' : promotionInfo.overlayFlag; // 倍数减免
      this.formParams.limitBig = promotionInfo.limitBig || ''; // 最高减免金额
      this.discountTable = this.isEmpty(promotionInfo.discountContent) ? [] : JSON.parse(promotionInfo.discountContent); // 多件折扣

      if (promotionInfo.containsTypes === '0') {
        this.selectedCategory = this.categoryOptions.map((item: any) => +item.groupId);
      } else {
        this.selectedCategory = promotionInfo.containsTypes ? promotionInfo.containsTypes.split(',').map((m: any) => +m) : [];
      }
      this.formParams.userType = promotionInfo.userType; // 参与人限制
      this.formParams.beginTime = promotionInfo.beginTime || ''; // 生效开始时间
      this.formParams.endTime = promotionInfo.endTime || ''; // 生效结束时间
      this.takeEffectDates = [promotionInfo.beginTime, promotionInfo.endTime]; // 活动生效时间dates
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 多件折扣
   * ----------------------------------------------------------------
   */
  addDiscountItem() {
    if (this.verifDiscountTable()) {
      this.message.warning('已添加项中存在未填写项，请先完善信息');
      return
    }
    if (this.discountTable.length < 5) {
      this.discountTable = [
        ...this.discountTable,
        {
          number: '',
          discountRate: '',
          maxReduction: ''
        }
      ]
    }
  }
  
  deleteDiscountItem(index: number) {
    this.discountTable = this.discountTable.filter((d: any, i: number) => i !== index);
  }

  verifDiscountTable() {
    let tempBool = this.discountTable.some((item: any) => {
      return !item.number || !item.discountRate || !item.maxReduction
    })

    return tempBool;
  }

  limitMinInput(index: number) {
    let minNum = 1;
    if (this.discountTable.length > 1 && index !== 0) {
      let preNum = this.discountTable[index - 1]['number'];
      minNum = preNum ? preNum + 1 : 1;
    }
    return minNum;
  }

  limitMaxInput(index: number) {
    let maxNum = Infinity;
    if (this.discountTable.length > 1 && index !== this.discountTable.length - 1) {
      let nextNum = this.discountTable[index + 1]['number'];
      maxNum = nextNum ? nextNum - 1 : Infinity;
    }
    return maxNum;
  }

  /**
   * ----------------------------------------------------------------
   * 发布 | 保存
   * ----------------------------------------------------------------
   */
  subRelease() {
    if (!this.isVerifForms()) {
      return
    }
    this.modal.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: '<b>确认发布?</b>',
      nzOnOk: () => {
        this.releaseLoading = true;
        this.submitForms(0);
      }
    });
  }
  
  async submitForms(type: number) {
    if (!this.isVerifForms()) {
      return
    }
    
    let params = {
      ...this.formParams,
      discountContent: this.discountTable.length ? JSON.stringify(this.discountTable) : '', // 多件折扣Table
      // isPlusCoupons: this.couponOverlay ? '0' : '1', // 优惠券叠加
      orderLimitMoney: this.isEmpty(this.formParams.orderLimitMoney) ? '0' : this.formParams.orderLimitMoney,
      limitSmall: this.isEmpty(this.formParams.limitSmall) ? '0' : this.formParams.limitSmall,
      limitBig: this.isEmpty(this.formParams.limitBig) ? '0' : this.formParams.limitBig,
      containsTypes: this.selectedCategory.length === this.categoryOptions.length ? '0' : this.selectedCategory.join(',')
    }

    this.preservationLoading = type == 0 ? true : false;
    // 发布状态为未开始1；新增 | 复制 状态为草稿5
    if (type === 0) {
      params.status = 1;
    } else {
      if (['0', '3'].includes(this.routeParams.type)) {
        params.status = 5;
      }
    }
    this.releaseLoading = false;
    this.preservationLoading = false;

    // return
    let res: any;
    if (['0', '3'].includes(this.routeParams.type)) {
      res = await this.services.addDescentItem(params);
    } else {
      params.id = this.routeParams.id;
      res = await this.services.updateDescentItem(params);
    }
    
    if (res.code === 0) {
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 验证
   * ----------------------------------------------------------------
   */
   isVerifForms() {
    if (this.isEmpty(this.formParams.name)) {
      this.message.warning('请输入活动名称');
      return false;
    } else if (this.isEmpty(this.formParams.showCopy)) {
      this.message.warning('请输入前端标题');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.orderLimitMoney)) {
      // ------ 满减 1 ------
      this.message.warning('请输入优惠门槛');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.limitSmall)) {
      // ------ 满减 1 ------
      this.message.warning('请输入减免额度');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.overlayFlag)) {
      // ------ 满减 1 ------
      this.message.warning('请选择倍数减免');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.orderLimitMoney)) {
      // ------ 折扣 2 ------
      this.message.warning('请输入优惠门槛');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.limitSmall)) {
      // ------ 折扣 2 ------
      this.message.warning('请输入折扣力度');
      return false;
    } else if (this.formParams.type === 2 &&this.isEmpty(this.formParams.limitBig)) {
      // ------ 折扣 2 ------
      this.message.warning('请输入最高减免金额');
      return false;
    } else if (this.formParams.type === 3 && !this.discountTable.length) {
      // ------ 多件折扣 3 ------
      this.message.warning('请先添加多件折扣优惠内容');
      return false;
    } else if (this.formParams.type === 3 && this.verifDiscountTable()) {
      // 多件折扣Table
      this.message.warning('多件折扣优惠内容存在未填写项');
      return false;
    } else if (!this.selectedCategory.length) {
      this.message.warning('请选择适用品类');
      return false;
    } else if (!this.takeEffectDates.length) {
      this.message.warning('请选择生效时间');
      return false;
    } else {
      return true;
    }
  }

  // 门槛验证
  thresholdVerif() {
    if (this.formParams.orderLimitMoney && this.formParams.orderLimitMoney > 0) {
      switch (this.formParams.type) {
        case 1:
          // console.log('满减券');
          if (Number(this.formParams.limitSmall) && Number(this.formParams.limitSmall) > Number(this.formParams.orderLimitMoney)) {
            this.message.warning('使用门槛值需大于或等于减免额度值!');
            this.formParams.orderLimitMoney = '';
          }
          break;
        case 3:
          // console.log('随机券');
          if (this.formParams.limitSmall && this.formParams.limitBig) {
            let tempMax = Math.max.apply(Math, [this.formParams.limitSmall, this.formParams.limitBig]);
            if (tempMax > this.formParams.orderLimitMoney) {
              this.message.warning('使用门槛值需大于或等于优惠金额最大值!');
              this.formParams.orderLimitMoney = '';
            }
          }
          break;
      }
    }
  }

  // 优惠门槛 | 减免额度验证
  discountLimitChange(num: number) {
    if (
      this.formParams.orderLimitMoney &&
      this.formParams.limitSmall &&
      this.formParams.orderLimitMoney <= this.formParams.limitSmall
    ) {
      switch (num) {
        case 0:
          // console.log('优惠门槛');
          this.message.warning('优惠门槛值需大于减免额度值');
          this.formParams.orderLimitMoney = '';
          return
        case 1:
          // console.log('减免额度');
          this.message.warning('减免额度值需小于优惠门槛值');
          this.formParams.limitSmall = '';
          return
      }
    }
  }

  /**
   * ----------------------------------------------------------------
   * Other
   * ----------------------------------------------------------------
   */
  couponTypeChange(event: number) {
    this.formParams.limitSmall = '' // 减免额度 | 折扣力度
    this.formParams.overlayFlag = '' // 倍数减免 0：否，1：是
    this.formParams.limitBig = '' // 最高减免金额
    this.discountTable = []; // 多件折扣Table
    this.formParams.orderLimitMoney = ''; // 优惠门槛

    if (event === 3) {
      this.formParams.orderLimitMoney = '0'; // 优惠门槛
    }
  }

  onDateChange(result: any[], kes: string[]) {
    this.formParams[kes[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[kes[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  // 有效期 Change
  effectiveChange(val: any) {
    this.formParams.limitTimeNum = 0;
    this.formParams.useBeginTime = '';
    this.formParams.useEndTime = '';
    this.takeEffectDates = [];
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // back
  back() {
    history.back();
  }
}
